#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include "Relay.h"

const size_t IPV4LEN = 15;
const size_t MAXSOCKADDRLEN = 100;
const char* ANYADDR = "0";
const char* IPV4_ANYADDR = "0.0.0";

SocketAddr::SocketAddr():
    m_port(0), m_str( "" )
{
    m_ip = IPV4_ANYADDR;
}

SocketAddr::SocketAddr( const char* buf, unsigned short p )
{
    m_port = p;
    if ( strlen(buf) > IPV4LEN || strcmp(buf, ANYADDR) == 0)
        m_ip = IPV4_ANYADDR;
    else
        m_ip = string( buf );
}

SocketAddr::~SocketAddr()
{
}

void
SocketAddr::setPort(unsigned short p)
{
    m_port = p;
}

void
SocketAddr::setAddress(const char *buf, unsigned short p)
{
    m_port = p;
    if (strlen(buf) <= IPV4LEN && strcmp(buf, ANYADDR) != 0)
    {
        m_ip = string(buf);
    }
}

sockaddr_in
SocketAddr::getAddr()
{
    struct sockaddr_in addr;
    bzero(&addr, sizeof(addr));
    addr.sin_addr.s_addr = inet_addr( m_ip.c_str() );
    addr.sin_family      = AF_INET;
    addr.sin_port        = htons( m_port );
    return addr;
}

bool
SocketAddr::getAddr(sockaddr_in &addr)
{
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port   = htons( m_port );
    return inet_pton(AF_INET, m_ip.c_str(), &addr.sin_addr) == 1 ?
        true : false;
}
